package com.ktwlsoft.archivemanage.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

import com.ktwlsoft.archivemanage.domain.business.businessService.ImgUploadService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.ImgsService;
import com.ktwlsoft.archivemanage.domain.dao.entity.Imgs;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.service.img.FileStorageService;
import com.ktwlsoft.archivemanage.service.utils.FileUtils;
import com.ktwlsoft.archivemanage.service.utils.SmartFileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import com.github.pagehelper.PageInfo;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 通用图片控制器
 *
 * @author zhuhe on 2019-07-17 11:07:06
 * @version 1.0
 */
@Api(value = "通用图片", description = "通用图片")
@RestController
@RequestMapping("currencyImg")
public class CurrencyImgController{

    /**日志对象*/
    private static Logger logger = LoggerFactory.getLogger(CurrencyImgController.class);

    /**
     * 通用图片
     */
    private final ImgsService imgsService;

    /**图片上传*/
    private final FileStorageService fileStorageService;

    public CurrencyImgController(ImgsService imgsService, FileStorageService fileStorageService) {
        this.imgsService = imgsService;
        this.fileStorageService = fileStorageService;
    }

    /**
     * 通用图片上传 on 2019-03-04 15:53:17
     *
     * @param request request
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "通用图片上传", httpMethod = "POST", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @PostMapping(value = "save")
    public ResponseEntity<?> save(HttpServletRequest request) {
        // 获取文件集合
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("files");
        // 业务id
        String businessId = request.getParameter("businessId");
        // 业务类型
        String businessType = request.getParameter("businessType");
        if (files.size() <= 0) {
            return ResponseEntity.ok(Result.body(null,ResultType.SAVING_ERROR).withMessage("文件为空"));
        }
        return ResponseEntity.ok(Result.ok(ImgUploadService.imgUploads(files,businessId,businessType)));
    }

    /**
     * 通用图片上传,传文件名称 on 2019-03-04 15:53:17
     *
     * @param request request
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "通用图片上传,传文件名称", httpMethod = "POST", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @PostMapping(value = "addImg")
    public ResponseEntity<?> addImg(HttpServletRequest request) {
        // 获取文件集合
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("files");
        // 业务id
        String businessId = request.getParameter("businessId");
        // 业务类型
        String businessType = request.getParameter("businessType");
        // 文件名称
        String name = request.getParameter("name");
        if (files.size() <= 0) {
            return ResponseEntity.ok(Result.body(null,ResultType.SAVING_ERROR).withMessage("文件为空"));
        }
        if(files.size() > 1){
            return ResponseEntity.ok(Result.body(null,ResultType.SAVING_ERROR).withMessage("一次只能传一张图片"));
        }
        if(name == null || "".equals(name.trim())){
            return ResponseEntity.ok(Result.body(null,ResultType.SAVING_ERROR).withMessage("名称不能为空"));
        }
        return ResponseEntity.ok(Result.ok(ImgUploadService.imgUploads(files,businessId,businessType,name)));
    }

    /**
     * 通用图片上传不写数据 on 2019-03-04 15:53:17
     *
     * @param request request
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "通用图片上传不写数据", httpMethod = "POST", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @PostMapping(value = "saveNoData")
    public ResponseEntity<?> saveNoData(HttpServletRequest request) {
        // 获取文件集合
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("files");
        if (files.size() <= 0) {
            return ResponseEntity.ok(Result.body(null,ResultType.SAVING_ERROR).withMessage("文件为空"));
        }
        return ResponseEntity.ok(Result.ok(ImgUploadService.imgUploadsNoData(files)));
    }

    /**
     * 分页 on 2019-07-17 11:07:06
     * @param pn 第几页
     * @param pageSize 每页多少条
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "分页", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @GetMapping(value = "findPage")
    public ResponseEntity<?> findPage(@RequestParam(defaultValue = "1") int pn,
                                      @RequestParam(defaultValue = "30") int pageSize,
                                      @ApiParam(name = "businessId", value = "业务id") @RequestParam(defaultValue = "", required = true) Long businessId,
                                      @ApiParam(name = "businessType", value = "业务类型") @RequestParam(defaultValue = "", required = true) String businessType){
        Imgs imgs = new Imgs();
        if(businessId != null && businessId != 0){
            imgs.setBusinessId(businessId);
        }
        if(businessType != null && !"".equals(businessType.trim())){
            imgs.setBusinessType(businessType);
        }
        imgs.setId(null);
        imgs.setCreatedAt(null);
        imgs.setUpdateAt(null);
        PageInfo<Imgs> page = imgsService.findPage(pn,pageSize,imgs);
        for(Imgs imgs1:page.getList()){
            if(imgs1.getFileName() != null) {
                // 名字转换
                String[] strArr = imgs1.getFileName().split("\\.");
                String fileNamePrefix = strArr[0];
                String fileNameSuffix = strArr[1];
                String finalFileName = null;
                try {
                    finalFileName = URLDecoder.decode(fileNamePrefix, "UTF-8") + "." + fileNameSuffix;
                } catch (UnsupportedEncodingException e) {
                    System.out.println("文件名字转换异常");
                    System.out.println(e.getMessage());
                }
                imgs1.setFileName(finalFileName);
            }
        }
        return ResponseEntity.ok(Result.ok(page));
    }

    /**
     * 批量物理删除 on 2019-07-17 11:07:06
     * @param ids	主键ID集合
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "批量物理删除", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @GetMapping(value = "deleteByIds")
    public ResponseEntity<?> deleteByIds(@ApiParam(name = "ids", value = "id集合") @RequestParam(defaultValue = "", required = true) List<Long> ids){
        if(ids == null || ids.size() <= 0){
            return ResponseEntity.ok(Result.body(null,ResultType.CHECK_ERROR).withMessage("id集合为空"));
        }
        //删除图片
        for(Long aLong:ids){
            Imgs imgs = imgsService.getById(aLong);
            if(imgs != null && imgs.getUrl() != null) {
                try {
                    FileUtils.deleteFile(fileStorageService.getStrPath(imgs.getUrl()));
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
            }
        }
        try {
            imgsService.deleteByIds(ids);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(null,ResultType.DELETE_ERROR));
        }
        return ResponseEntity.ok(Result.ok(ids));
    }


    /**
     * 物理删除 on 2019-07-17 11:07:06
     * @param id	主键
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "物理删除", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @GetMapping(value = "deleteById")
    public ResponseEntity<?> deleteById(@ApiParam(name = "id", value = "id") @RequestParam(defaultValue = "", required = true)Long id){
        return ResponseEntity.ok(ImgUploadService.deleteById(id));
    }

    /**
     * 文件预览 on 2019/3/12 0012 16:36
     *
     * @return ResponseEntity<Resource>
     */
    @ApiOperation(value = "文件预览", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @GetMapping("/getFileView/{fileId:.+}")
    public ResponseEntity<Resource> getFileView(@PathVariable Long fileId, HttpServletRequest request) {
        if(fileId == null || fileId == 0){
            return null;
        }
        Imgs imgs = imgsService.getById(fileId);
        // Load file as Resource
        Resource resource = fileStorageService.loadFileAsResource(imgs.getUrl());
        // Try to determine file's content type
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            logger.info("Could not determine file type.");
        }
        // Fallback to the default content type if type could not be determined
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)).body(resource);
    }

    /**
     * 文件Url预览 on 2019/3/12 0012 16:36
     *
     * @return ResponseEntity<Resource>
     */
    @ApiOperation(value = "文件Url预览", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @GetMapping("getFileUrlView")
    public ResponseEntity<Resource> getFileUrlView(String url, HttpServletRequest request) {
        if(url == null || "".equals(url)){
            return null;
        }
        // Load file as Resource
        Resource resource = fileStorageService.loadFileAsResource(url);
        // Try to determine file's content type
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            logger.info("Could not determine file type.");
        }
        // Fallback to the default content type if type could not be determined
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        // 名字转换
        String[] strArr = resource.getFilename().split("\\.");
        String fileNamePrefix = strArr[0];
        String fileNameSuffix = strArr[1];
        String finalFileName = null;
        try {
            finalFileName = URLDecoder.decode(fileNamePrefix, "UTF-8") + "." + fileNameSuffix;
        } catch (UnsupportedEncodingException e) {
            System.out.println("文件名字转换异常");
            System.out.println(e.getMessage());
        }
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
                .header("attachment; filename=\"" + finalFileName + "\"")
                .body(resource);
    }

    /**
     * 文件下载 on 2019/12/30 15:40
     *
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "文件下载", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @GetMapping(value = "download")
    public ResponseEntity<?> download(@ApiParam(name = "id", value = "图片id") @RequestParam Long id, HttpServletRequest request) {
        return imgsService.download(id, request);
    }

    /**
     * 文件下载 on 2019/12/30 15:40
     *
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "文件下载", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @GetMapping("/downloadFile/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) {
        // 获取文件
        return resultFile(fileStorageService.loadFileAsResource(fileName),request);
    }

    /**
     * 文件下载通过url on 2019/12/30 15:40
     *
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "文件下载通过url", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @GetMapping("downloadFileByUrl")
    public ResponseEntity<Resource> downloadFileByUrl(String url, HttpServletRequest request) {
        // 获取文件
        return resultFile(fileStorageService.loadFileAsResource(url),request);
    }

    /**
     * 通过url获取视频缩略图 on 2019/12/30 15:40
     *
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "通过url获取视频缩略图", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @GetMapping("getVideoThumbnail")
    public ResponseEntity<Resource> getVideoThumbnail(String url, HttpServletRequest request) {
        String[] strings = url.length() > 0?url.split("\\."):null;
        String suffix = strings != null?strings[strings.length - 1]:null;
        String path = null;
        if(suffix != null && "mp4".equals(suffix)){
            try {
                path = SmartFileUtils.videoImage(fileStorageService.getStrPath(url));
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            path = url;
        }
        return getFileUrlView(path,request);
    }

    /**
     * 返回文件 on 2020/5/25 14:55
     *
     * @param resource resource
     * @param request request
     * @return ResponseEntity<Resource>
     */
    private ResponseEntity<Resource> resultFile(Resource resource,HttpServletRequest request){
        // 确定文件的内容类型
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            logger.info("无法确定文件类型");
        }
        // 如果无法确定类型，则回退到默认内容类型
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        // 名字转换
        String[] strArr = resource.getFilename().split("\\.");
        String fileNamePrefix = strArr[0];
        String fileNameSuffix = strArr[1];
        String finalFileName = null;
        try {
            finalFileName = URLDecoder.decode(fileNamePrefix, "UTF-8") + "." + fileNameSuffix;
        } catch (UnsupportedEncodingException e) {
            System.out.println("文件名字转换异常");
            System.out.println(e.getMessage());
        }
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + finalFileName + "\"")
                .body(resource);
    }
}
